package org.cars.netty.server.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

/**
 * 服务端心跳handler
 *
 * @author wang
 * @version 1.0
 * @date 2023/9/6 18:11
 */
public class HeartBeatHandler extends ChannelDuplexHandler {

    private static final String HEARTBEAT = "heartbeat";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf buf) {
            //如果是心跳包, 直接丢弃, 不做处理
            if (HEARTBEAT.equals(buf.toString(CharsetUtil.UTF_8))) {
                System.out.println("服务端接收到心跳包");
                return;
            }
        }
        super.channelRead(ctx, msg);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
        if (event instanceof IdleStateEvent evt) {
            if (evt.state().equals(IdleState.READER_IDLE)) {
                //发送一个心跳包
                byte[] bytes = HEARTBEAT.getBytes(StandardCharsets.UTF_8);
                ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
                buffer.writeBytes(bytes);
                ctx.channel().writeAndFlush(buffer);
            }
        }
    }
}